package com.ceba.be.api.utils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class APIHttpClient {
	// 接口地址  
    private static String apiURL = "http://192.168.3.67:8080/lkgst_manager/order/order";  
    private Log logger = LogFactory.getLog(this.getClass());  
    private static final String pattern = "yyyy-MM-dd HH:mm:ss:SSS";  
    private CloseableHttpClient httpClient = null;  
    private HttpPost method = null;  
    private long startTime = 0L;  
    private long endTime = 0L;  
    private int status = 0;  
  
    /** 
     * 接口地址 
     *  
     * @param url 
     */  
    public APIHttpClient(String url) {  
  
        if (url != null) {  
            this.apiURL = url;  
        }  
        if (apiURL != null) {  
            httpClient = HttpClients.createDefault();
            method = new HttpPost(apiURL);  
  
        }  
    }  
  
    /** 
     * 调用 API 
     *  
     * @return
     */  
    public String post() {  
        String body = null;  
        if (method != null) {  
            try {  
  
                // 建立一个NameValuePair数组，用于存储欲传送的参数  
                method.addHeader("Content-type","text/plain"+"; charset=utf-8");  
                startTime = System.currentTimeMillis();  
  
                HttpResponse response = httpClient.execute(method);  
                  
                endTime = System.currentTimeMillis();  
                int statusCode = response.getStatusLine().getStatusCode();  
                  
                if (statusCode != HttpStatus.SC_OK) {  
                    logger.error("Method failed:" + response.getStatusLine());  
                    status = 1;  
                }  
  
                body = getRespString(response.getEntity());  
  
            } catch (IOException e) {  
                // 网络错误  
                status = 3;  
            } catch (Exception e) {
				e.printStackTrace();
			} finally {  
            }  
  
        }  
        return body;  
    }
    
    /** 
     * 调用 API 
     *  
     * @param parameters 
     * @return 
     */  
    public String post(String parameters,String paramType) {  
        String body = null;  
        logger.info("parameters:" + parameters);  
  
        if (method != null & parameters != null  
                && !"".equals(parameters.trim())) {  
            try {  
  
                // 建立一个NameValuePair数组，用于存储欲传送的参数  
                method.addHeader("Content-type",paramType+"; charset=utf-8");  
                method.setHeader("Accept", paramType);  
                method.setEntity(new StringEntity(parameters, Charset.forName("UTF-8")));  
                startTime = System.currentTimeMillis();  
  
                HttpResponse response = httpClient.execute(method);  
                  
                endTime = System.currentTimeMillis();  
                int statusCode = response.getStatusLine().getStatusCode();  
                  
                logger.info("statusCode:" + statusCode);  
                logger.info("调用API 花费时间(单位：毫秒)：" + (endTime - startTime));  
                if (statusCode != HttpStatus.SC_OK) {  
                    logger.error("Method failed:" + response.getStatusLine());  
                    status = 1;  
                }  
  
                // Read the response body  
                body = getRespString(response.getEntity());  
  
            } catch (IOException e) {  
                // 网络错误  
                status = 3;  
            } catch (Exception e) {
				e.printStackTrace();
			} finally {  
                logger.info("调用接口状态：" + status);  
            }  
  
        }  
        return body;  
    }

    public String uploadFileImpl(String serverUrl, String localFilePath,  
            String serverFieldName, Map<String, String> params,String type)  
            throws Exception {  
        String respStr = null;  
        try {  
            FileBody binFileBody = new FileBody(new File(localFilePath));

            /**
             * setMode(HttpMultipartMode.RFC6532)函数用以支持中文文件名；服务器端收到文件名后，会以"iso-8859-1"字符集解码
             */
            MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder  
                    .create().setMode(HttpMultipartMode.RFC6532);
            // add the file params
            multipartEntityBuilder.addPart(serverFieldName, binFileBody);  
            // 设置上传的其他参数  
            setUploadParams(multipartEntityBuilder, params,type);
            HttpEntity reqEntity = multipartEntityBuilder.build();  
            method.setEntity(reqEntity);  
  
            HttpResponse response = httpClient.execute(method);  
            System.out.println(response.getStatusLine());  
            HttpEntity resEntity = response.getEntity();  
            
            respStr = getRespString(resEntity);
            EntityUtils.consume(resEntity);  
        } finally {  
        	httpClient.close();  
        }  
        System.out.println("resp=" + respStr);  
        return respStr;  
    }   
  
    public String uploadData(String serverUrl, Map<String, String> params )  
            throws Exception {  
        String respStr = null;  
        try {  
  
            // 创建参数队列    
            List<NameValuePair> formparams = new ArrayList<NameValuePair>();  
            formparams.add(new BasicNameValuePair("json", params.get("json")));  
            formparams.add(new BasicNameValuePair("base", params.get("base")));  
            
            UrlEncodedFormEntity uefEntity =new UrlEncodedFormEntity(formparams, "UTF-8");  
            method.setEntity(uefEntity);  
            
            HttpResponse response = httpClient.execute(method);  
            System.out.println(response.getStatusLine());  
            HttpEntity resEntity = response.getEntity();  
            
            //respStr = EntityUtils.toString(resEntity);    
            respStr = getRespString(resEntity);
            EntityUtils.consume(resEntity);  
        } finally {  
        	httpClient.close();  
        }  
        System.out.println("resp=" + respStr);  
        return respStr;  
    }   
  


	/** 
     * 设置上传文件时所附带的其他参数 
     *  
     * @param multipartEntityBuilder 
     * @param params 
	 * @throws UnsupportedEncodingException 
     */  
    private void setUploadParams(MultipartEntityBuilder multipartEntityBuilder,  
            Map<String, String> params,String type) throws UnsupportedEncodingException {  
        if (params != null && params.size() > 0) {  
            Set<String> keys = params.keySet();  
            for (String key : keys) {
            	if(type.equals("json")){
            		multipartEntityBuilder  
                        .addPart(key, new StringBody(params.get(key),  
                                ContentType.APPLICATION_JSON));  
            	}else if(type.equals("text")){
            		multipartEntityBuilder  
                    .addPart(key, new StringBody(params.get(key),Charset.forName("utf-8")));
            	}
            }  
        }  
    }  
  
    /** 
     * 将返回结果转化为String 
     *  
     * @param entity 
     * @return 
     * @throws Exception 
     */  
    private String getRespString(HttpEntity entity) throws Exception {  
        if (entity == null) {  
            return null;  
        }  
        InputStream is = entity.getContent();  
        StringBuffer strBuf = new StringBuffer();  
        byte[] buffer = new byte[4096];  
        int r = 0;  
        while ((r = is.read(buffer)) > 0) {  
            strBuf.append(new String(buffer, 0, r, "UTF-8"));  
        }  
        return strBuf.toString();  
    }  
  
}  
